<template>
  <div id="biye2">
    <div class="step-one">
      <div class="s-title">毕业要求通用标准</div>
      <div class="s-content">
        <div>专业必须有明确、公开、可衡量的毕业要求,毕业要求应能支撑培养目标的达成。专业制定的毕业要求应完全覆盖12条通用标准。</div>
      </div>
    </div>
    <div class="step-three">
      <div class="s-right">
        <div
          class="s-btn"
          @click="addNewParentItem"
        >
          <el-icon>
            <CirclePlus />
          </el-icon>
          毕业要求
        </div>
      </div>
      <div class="three-table">
        <div>
          <div class="three-row">
            <div class="three-num three-blue">指标点</div>
            <div class="three-content three-blue">分解内容</div>
            <div class="three-tools"></div>
          </div>
        </div>
        <div
          v-for="(item,index) in tableData"
          :key="item.id"
        >
          <div class="three-row three-head">
            <div class="three-num">{{ index+1 }}</div>
            <div class="three-content">
              <el-input
                v-if="item.isEditing"
                v-model="item.content"
                size="small"
              />
              <span v-else>{{ item.content }}</span>
            </div>
            <div class="three-tools">
              <div
                v-if="item.isEditing"
                class="three-btn"
              >
                <div @click="editTable(item)">
                  <el-icon>
                    <Check />
                  </el-icon>
                </div>
                <div @click="handleEditCancel(item)">
                  <el-icon>
                    <Close />
                  </el-icon>
                </div>
              </div>
              <div
                v-else
                class="three-btn"
              >
                <div @click="handleEdit(item)">编辑</div>
                <div @click="deleteTable(item)">删除</div>
              </div>
            </div>
          </div>
          <div
            class="three-row"
            v-for="(item2,index2) in item.children"
            :key="item2.id"
          >
            <div class="three-num">{{ index+1 }}-{{ index2+1 }}</div>
            <div class="three-content">
              <el-input
                v-if="item.isEditing"
                v-model="item2.content"
                size="small"
              />
              <span v-else>{{ item2.content }}</span>
            </div>
            <div class="three-tools">
              <div
                v-if="item.isEditing"
                class="three-btn"
                @click="removeChild(item, item2)"
              >
                <div>
                  <el-icon>
                    <Delete />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
          <div
            v-if="item.isEditing"
            class="add-row"
            @click="addNewChild(item)"
          >
            <el-icon>
              <Plus />
            </el-icon>
            指标点
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
  
  <script>
export default {
  components: {},
  data() {
    return {
      originalData: {},
      editTwo: false,
      twoMessage:
        "培养系统地掌握数学、自然科学基础知识和计算机科学与技术专业基础知识，具备较坚实的理论基础，获得计算加专业良好的科学思维和系统的工程训练，具备良好的分析问题解决问题的能力及良好外语运用能力，具有强烈的自主学习意识和创新意识，科学型和工程型相结合的计算机专业高级人才。",
      tableData: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //删除
    deleteTable(row) {
      this.$confirm("此操作将永久删除该条信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: "删除中...",
          background: "rgba(0, 0, 0, 0.7)",
        });
        const url = "/tes/graduation/requirements";
        const params = {
          id: row.id,
        };
        this.$axios
          .delete(url, { params })
          .then((response) => {
            const res = response;
            this.$message.success(res.message || "删除成功");
            loading.close();
            this.getList();
          })
          .finally(() => {});
      });
    },
    //前端删除子项
    removeChild(parentItem, childItem) {
      // 弹窗确认（可选）
      this.$confirm("确定删除该指标点吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          // 找到子项索引并删除
          const index = parentItem.children.indexOf(childItem);
          if (index !== -1) {
            parentItem.children.splice(index, 1);
          }

          // 可选：重新排序 number
          parentItem.children.forEach((child, i) => {
            child.number = i + 1;
          });

          this.$message({
            type: "success",
            message: "删除成功",
          });
        })
        .catch(() => {
          // 取消删除
        });
    },
    //新增父项
    addNewParentItem() {
      const newId = -Date.now(); // 临时 ID

      const newItem = {
        name: "", // 可根据需要设默认值
        content: "",
        isEditing: true, // 直接进入编辑模式
        children: [
          // 可选：自动添加一个空子项
          // {
          //   name: "",
          //   content: "",
          //   number: 1,
          //   isNew: true,
          // },
        ],
        isNew: true, // 标记为新增项
      };

      this.tableData.push(newItem);

      // ✅ 备份原始数据（用于取消时恢复）
      this.$nextTick(() => {
        this.originalData[newId] = JSON.parse(JSON.stringify(newItem));
      });
    },
    //加一行
    addNewChild(parentItem) {
      const newId = -Date.now(); // 使用负时间戳作为临时 ID（避免与后端 ID 冲突）
      const newIndex = parentItem.children.length + 1;

      const newChild = {
        name: "",
        content: "", // 空内容，用户填写
        number: newIndex, // 自动递增编号
        isNew: true, // 标记为新增项，可用于样式或提交判断
      };

      parentItem.children.push(newChild);
    },
    //确认修改
    editTable(row) {
      console.log(row, "1");
      let parentRow = {
        id: row.id,
        content: row.content,
      };
      let newRow = [...row.children];
      newRow.unshift(parentRow);
      console.log(newRow, "2");
      this.saveList(newRow);
    },
    handleEdit(row) {
      // 深拷贝整个对象（包括 children）
      this.originalData[row.id] = JSON.parse(JSON.stringify(row));
      row.isEditing = true;
    },

    handleEditCancel(row) {
      if (row.id && this.originalData[row.id]) {
        const original = this.originalData[row.id];
        // 先恢复 children，再恢复其他字段
        row.children = original.children.map((c) => ({ ...c }));
        Object.keys(original).forEach((key) => {
          if (key !== "children") {
            row[key] = original[key];
          }
        });
      } else {
        this.tableData.splice(this.tableData.indexOf(row), 1);
      }
      row.isEditing = false;
    },
    //获取
    getList() {
      const url = "/tes/graduation/requirements";
      this.loadingTarget = true;
      this.$axios
        .get(url)
        .then((response) => {
          const res = response.data;
          this.tableData = res;
          console.log(res);
        })
        .finally(() => {});
    },
    //保存
    saveList(row) {
      const url = "/tes/graduation/requirements";
      const data = row;
      this.$axios
        .post(url, data)
        .then((response) => {
          const res = response;
          row.isEditing = false;
          this.$message.success(res.message || "请求成功");
          this.getList();
        })
        .finally(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
#biye2 {
  background: #ffffff;
  box-shadow: 0px 0px 7px 0px rgba(70, 123, 235, 0.13);
  border-radius: 10px;
  border: 1px solid #ffffff;
  padding: 26px;
  box-sizing: border-box;
  .s-right {
    transform: translate(0px, 33px);
    display: flex;
    justify-content: flex-end;
    .el-icon {
      font-size: 20px;
    }
  }
  .s-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 4px;
    background: #457aff;
    border-radius: 4px;
    font-size: 14px;
    color: #ffffff;
    padding: 9px 15px;
    cursor: pointer;
    &:hover {
      background: #3a68c7;
    }
  }
  .step-one {
    .s-title {
      font-size: 16px;
      color: #1e2c48;
      margin-bottom: 10px;
    }
    .s-content {
      font-size: 14px;
      color: #71778f;
      line-height: 24px;
    }
  }
  .step-two {
    margin-bottom: 60px;
    .s-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      color: #1e2c48;
      margin-bottom: 14px;
    }
    .s-content {
      font-size: 14px;
      color: #1e2c48;
      border-radius: 4px;
      border: 1px solid #ededed;
      padding: 15px 22px;
      line-height: 24px;
    }
    .s-input {
      :deep(.el-textarea__inner) {
        padding: 15px 22px;
        line-height: 24px;
        border-radius: 4px;
      }
    }
  }
  .step-three {
    .my-table {
      :deep(th) {
        .cell {
          font-weight: bold;
          font-size: 14px;
          color: #7a8cb0;
        }
      }
    }
    .three-table {
      > div {
        .three-row {
          display: flex;
          justify-content: space-between;
          border-bottom: 1px solid #e0e2e8;
          color: #1e2c48;
          font-size: 14px;
          &.three-head {
            font-weight: bold;
            padding: 10px 0;
          }

          > div {
            // height: 40px;
            line-height: 30px;
            padding: 4px 0;
          }
          .three-blue {
            font-weight: bold;
            font-size: 14px;
            color: #7a8cb0;
          }
          .three-num {
            min-width: 100px;
          }
          .three-content {
            flex: 1;
            overflow: hidden;
            display: flex;
            align-items: center;
            :deep(.el-input__inner) {
              height: 32px;
              font-size: 14px;
            }
          }
          .three-tools {
            min-width: 200px;
            display: flex;
            justify-content: center;
            align-items: center;
            .three-btn {
              display: flex;
              gap: 10px;
              font-weight: normal;
              > div {
                color: #457aff;
                cursor: pointer;
                .el-icon {
                  font-size: 16px;
                }
                &:hover {
                  color: #3a68c7;
                }
              }
            }
          }
        }
        .add-row {
          display: flex;
          justify-content: center;
          align-items: center;
          gap: 10px;
          font-size: 14px;
          color: #457aff;
          height: 34px;
          background: #ffffff;
          border-radius: 4px;
          border: 1px solid #457aff;
          margin: 10px 0;
          cursor: pointer;
          &:hover {
            color: #fff;
            background: #457aff;
          }
        }
      }
    }
  }
}
</style>